package com.party.jackclientandroid.ui_home.fragment;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.Service;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestBuilder;
import com.party.jackclientandroid.BaseActivity;
import com.party.jackclientandroid.BaseFragment;
import com.party.jackclientandroid.MainActivity;
import com.party.jackclientandroid.R;
import com.party.jackclientandroid.api.DefaultConsumer;
import com.party.jackclientandroid.api.VideoCommentService;
import com.party.jackclientandroid.api.VideoService;
import com.party.jackclientandroid.bean.BaseResult;
import com.party.jackclientandroid.bean.GrabRedPacketBean;
import com.party.jackclientandroid.bean.PlayerInfoBean;
import com.party.jackclientandroid.bean.VideoCommentBean;
import com.party.jackclientandroid.bean.VideoDetail;
import com.party.jackclientandroid.controller.AddVideoCommentListener;
import com.party.jackclientandroid.controller.DialogController;
import com.party.jackclientandroid.controller.TCVodPlayerController;
import com.party.jackclientandroid.event.AMapBeanEvent;
import com.party.jackclientandroid.event.ReLoginSuccessEvent;
import com.party.jackclientandroid.litvideo.common.utils.TCUtils;
import com.party.jackclientandroid.litvideo.login.TCUserMgr;
import com.party.jackclientandroid.litvideo.play.TCVideoInfo;
import com.party.jackclientandroid.loadviewhelper.load.LoadViewHelper;
import com.party.jackclientandroid.ui_home.activity.ShopDetailActivity;
import com.party.jackclientandroid.utils.NetworkUtils;
import com.party.jackclientandroid.utils.SoundPoolUtils;
import com.party.jackclientandroid.view.dialog.DeletePictureDialog;
import com.party.jackclientandroid.view.dialog.RedPacketDialogCopy;
import com.party.jackclientandroid.view.dialog.VideoCommentDialog;
import com.sackcentury.shinebuttonlib.ShineButton;
import com.tencent.liteav.basic.log.TXCLog;
import com.tencent.rtmp.ITXVodPlayListener;
import com.tencent.rtmp.TXLiveConstants;
import com.tencent.rtmp.TXLog;
import com.tencent.rtmp.TXVodPlayConfig;
import com.tencent.rtmp.TXVodPlayer;
import com.tencent.rtmp.ui.TXCloudVideoView;
import com.tencent.ugc.TXVideoInfoReader;

import org.greenrobot.eventbus.Subscribe;

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import de.hdodenhof.circleimageview.CircleImageView;
import fr.castorflex.android.verticalviewpager.VerticalViewPager;
import io.reactivex.functions.Consumer;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * 首页-众享
 */
public class ShareFragment extends BaseFragment implements ITXVodPlayListener {
    private static final String TAG = "TCVodPlayerActivity";
    private VerticalViewPager mVerticalViewPager;
    private VideoListPagerAdapter mPagerAdapter;
    private TXCloudVideoView mTXCloudVideoView;
    private ImageView mIvCover;
    private ImageView mIvPlay;
    // 合拍相关
    private ProgressDialog mDownloadProgressDialog;
    // 发布者id 、视频地址、 发布者名称、 头像URL、 封面URL
    private List<PlayerInfoBean> mTCLiveInfoList;
    private int mInitTCLiveInfoPosition;
    private int mCurrentPosition;
    @BindView(R.id.main_layout)
    RelativeLayout mRelativeLayout;

    private int newPayCount;

    /**
     * SDK播放器以及配置
     */
    private TXVodPlayer mTXVodPlayer;
    private PhoneStateListener mPhoneListener = null;
    private boolean isVisibleToUser;
    private SwipeRefreshLayout mSwipeRefreshLayout;
    private Handler mHandler;
    /**
     * 由于在Fragment里面会出现第一次第一个不能播放,向下滑动再返回就播放正常;暂时解决问题
     */
    private boolean firstCreate = true;
    TCVodPlayerController playerController;
    VideoService videoService;
    VideoCommentService videoCommentService;
    double longitude;
    double latitude;
    int type;
    DecimalFormat df = new DecimalFormat("0.00");

    class PlayerInfo {
        public TXVodPlayer txVodPlayer;
        public String playURL;
        public boolean isBegin;
        public View playerView;
        public int pos;
        public int reviewstatus;
    }

    public static ShareFragment newInstance() {
        ShareFragment fragment = new ShareFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_share;
    }

    @Override
    protected void initData() {
        mTCLiveInfoList = new ArrayList<>();
        mHandler = new Handler();
        mSwipeRefreshLayout = mView.findViewById(R.id.srl);
        helper = new LoadViewHelper(mRelativeLayout);
        helper.setListener(() -> {
            helper.showLoading();
            getNeedVideoData();
        });

        videoCommentService = new VideoCommentService((BaseActivity) mActivity);
        videoService = new VideoService((BaseActivity) mActivity);
        playerController = new TCVodPlayerController(this);
        mSwipeRefreshLayout.setEnabled(false);
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getNeedData();
            }
        });
        if (mApplication.getMap() != null) {
            longitude = mApplication.getMap().getLongitude();
            latitude = mApplication.getMap().getLatitude();
            type = 1;
            helper.showLoading();
            addDisposableIoMain(videoService.listVideo(longitude, latitude, type), new DefaultConsumer<List<PlayerInfoBean>>(mApplication) {
                @Override
                public void operateSuccess(BaseResult<List<PlayerInfoBean>> result) {
                    helper.showContent();
                    newPayCount = result.getData().size();
                    ((MainActivity) getActivity()).setUpdateTab(newPayCount);
                    if (result.getData() != null && result.getData().size() > 0) {
                        mTCLiveInfoList.clear();
                        mTCLiveInfoList.addAll(result.getData());
                        initDatas();
                        initPlayerSDK();
                        initPhoneListener();
//                        mPagerAdapter.notifyDataSetChanged();
                    }
                }

                @Override
                public void operateError(String message) {
                    helper.showEmpty(message);
                }
            });
        }

    }

    public void getNeedVideoData() {
        longitude = mApplication.getMap().getLongitude();
        latitude = mApplication.getMap().getLatitude();
        type = 1;
        addDisposableIoMain(videoService.listVideo(longitude, latitude, type), new DefaultConsumer<List<PlayerInfoBean>>(mApplication) {
            @Override
            public void operateSuccess(BaseResult<List<PlayerInfoBean>> result) {
                helper.showContent();
                newPayCount = result.getData().size();
                ((MainActivity) getActivity()).setUpdateTab(newPayCount);
                if (result.getData() != null && result.getData().size() > 0) {
                    mTCLiveInfoList.addAll(result.getData());
                    mPagerAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void operateError(String message) {
                helper.showEmpty(message);
            }
        });
    }

    /**
     * 领取红包
     *
     * @param dialog
     * @param position
     */
    public void grabMoney(final RedPacketDialogCopy dialog, final int position) {
        String videoId = mTCLiveInfoList.get(position).getVideoId();
        addDisposableIoMain(videoService.grabRedEnvelope(videoId), new DefaultConsumer<GrabRedPacketBean>(mApplication) {
            @Override
            public void operateError(String message) {
                super.operateError(message);
                dialog.restartGrabAnim();
            }

            @Override
            public void operateSuccess(BaseResult<GrabRedPacketBean> result) {
                setNotRadBag(position);
                if (result.getData() == null) {
                    dialog.setTitleSize(20);
                    dialog.setTitle("红包已被抢完");
                } else {
                    // 由于钱为分单位
                    float value = 0f;
                    try {
                        value = Integer.parseInt(result.getData().getMoney()) / 100f;
                    } catch (Exception e) {
                    }
                    String moneyStr = df.format(value);
                    if (moneyStr.equals("0.00")) {
                        dialog.setTitleSize(20);
                        dialog.setTitle("红包已被抢完");
                        dialog.setMoneyTips(false);
                        dialog.setTips(false);
                    } else {
                        dialog.setTitleSize(40);
//                        dialog.setTitle("¥ " + moneyStr);
                        dialog.setTitle(moneyStr);
                        dialog.setMoneyTips(true);
                        dialog.setTips(true);
                    }
                }
                dialog.setMessage("");
                dialog.stopGrabAnim(false);
                new SoundPoolUtils(mActivity).loadNeedVoice();
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        dialog.dismiss();
                    }
                }, 1500L);
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {
                showToast(throwable.getMessage());
                dialog.restartGrabAnim();
            }
        });
    }

    //设置没有红包
    public void setNotRadBag(int position) {
        mTCLiveInfoList.get(position).getVideoDetail().setHaveRedBag(0);
        handleRedBag(position);
    }


    /**
     * 获取数据
     */
    private void getNeedData() {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                mSwipeRefreshLayout.setRefreshing(false);
            }
        }, 2000L);
    }

    /**
     * 这里是直接调用transaction.hide使用
     */
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        this.isVisibleToUser = !hidden;
        if (isVisibleToUser) {
            // 如果红包正在显示
            if (playerController.isShowRedPacketDialog()) return;
            // 由于在Fragment里面会出现第一次第一个不能播放,向下滑动再返回就播放正常;暂时解决问题
            if (firstCreate) {
                if (mTCLiveInfoList.size() > 1) {
                    mVerticalViewPager.setCurrentItem(1, false);
                    mVerticalViewPager.setCurrentItem(0, false);
                    firstCreate = false;
                }
            }
            boolean wifiIsConnect = NetworkUtils.wifiIsConnect();
            if (!wifiIsConnect) {
                if (mTXCloudVideoView != null) {
                    mTXCloudVideoView.onPause();
                }
                if (mTXVodPlayer != null) {
                    mTXVodPlayer.pause();
                }
                if (mIvPlay != null) mIvPlay.setVisibility(View.VISIBLE);
                DialogController.showVideoPictureDialog(mActivity, "非WiFi环境是否播放视频", new DeletePictureDialog.OkListener() {
                    @Override
                    public void deletePicture(int position) {
                        if (mTXCloudVideoView != null) {
                            mTXCloudVideoView.onResume();
                        }
                        if (mTXVodPlayer != null) {
                            mTXVodPlayer.resume();
                        }
                        if (mIvPlay != null) mIvPlay.setVisibility(View.INVISIBLE);
                    }
                });
                return;
            }
            if (mTXCloudVideoView != null) {
                mTXCloudVideoView.onResume();
            }
            if (mTXVodPlayer != null) {
                mTXVodPlayer.resume();
            }
            if (mIvPlay != null) {
                mIvPlay.setVisibility(View.INVISIBLE);
            }
        } else {
            if (mTXCloudVideoView != null) {
                mTXCloudVideoView.onPause();
            }
            if (mTXVodPlayer != null) {
                mTXVodPlayer.pause();
            }
            if (mIvPlay != null) {
                mIvPlay.setVisibility(View.VISIBLE);
            }
        }
    }

    /**
     * 这里是直接调用transaction.show使用
     */
    @Override
    public void onResume() {
        super.onResume();
        if (mActivity instanceof MainActivity) {
            if (((MainActivity) mActivity).getChooseTabNum() == 2) {
                onHiddenChanged(false);
            }
        }
    }

    protected void stopPlay(boolean clearLastFrame) {
        if (mTXVodPlayer != null) {
            mTXVodPlayer.stopPlay(clearLastFrame);
        }
    }

    /**
     * 停止播放
     */
    public void pausePlayVideo() {
        if (mTXVodPlayer != null) {
            mTXVodPlayer.pause();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mTXCloudVideoView != null) {
            mTXCloudVideoView.onDestroy();
            mTXCloudVideoView = null;
        }
        stopPlay(true);
        mTXVodPlayer = null;

        if (mPhoneListener != null) {
            TelephonyManager tm = (TelephonyManager) mApplication.getSystemService(Service.TELEPHONY_SERVICE);
            tm.listen(mPhoneListener, PhoneStateListener.LISTEN_NONE);
            mPhoneListener = null;
        }
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
        followMap.clear();
    }

    @Override
    public void onPlayEvent(TXVodPlayer player, int event, Bundle param) {
        if (event == TXLiveConstants.PLAY_EVT_CHANGE_RESOLUTION) {
            int width = param.getInt(TXLiveConstants.EVT_PARAM1);
            int height = param.getInt(TXLiveConstants.EVT_PARAM2);
            if (width > height) {
                player.setRenderRotation(TXLiveConstants.RENDER_ROTATION_LANDSCAPE);
            } else {
                player.setRenderRotation(TXLiveConstants.RENDER_ROTATION_PORTRAIT);
            }
        } else if (event == TXLiveConstants.PLAY_EVT_PLAY_END) {
            PlayerInfo playerInfo = mPagerAdapter.findPlayerInfo(player);
            if (mTCLiveInfoList.get(playerInfo.pos).getVideoDetail().getHaveRedBag() == 0) {
                mIvPlay.setVisibility(View.VISIBLE);
                restartPlay();
            } else {
                mIvPlay.setVisibility(View.INVISIBLE);
                playerController.handleVideoPlayEnd(mTCLiveInfoList.get(playerInfo.pos), playerInfo.pos);
            }
        } else if (event == TXLiveConstants.PLAY_EVT_RCV_FIRST_I_FRAME) {// 视频I帧到达，开始播放
            PlayerInfo playerInfo = mPagerAdapter.findPlayerInfo(player);
            if (playerInfo != null) {
                playerInfo.isBegin = true;
            }
            if (mTXVodPlayer == player) {
                TXLog.i(TAG, "onPlayEvent, event I FRAME, player = " + player);
                mIvCover.setVisibility(View.GONE);
                mIvPlay.setVisibility(View.INVISIBLE);
                TCUserMgr.getInstance().uploadLogs("vodplay", TCUserMgr.getInstance().getUserId(), event, "点播播放成功", new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                    }
                });
            }
        } else if (event == TXLiveConstants.PLAY_EVT_VOD_PLAY_PREPARED) {
            if (mTXVodPlayer == player) {
                TXLog.i(TAG, "onPlayEvent, event prepared, player = " + player);
                if (isVisibleToUser) {
                    mTXVodPlayer.resume();
                    mIvPlay.setVisibility(View.INVISIBLE);
                }
            }
        } else if (event == TXLiveConstants.PLAY_EVT_PLAY_BEGIN) {
            PlayerInfo playerInfo = mPagerAdapter.findPlayerInfo(player);
            if (playerInfo != null && playerInfo.isBegin) {
                mIvCover.setVisibility(View.GONE);
                mIvPlay.setVisibility(View.INVISIBLE);
                TXCLog.i(TAG, "onPlayEvent, event begin, cover remove");
            }
        } else if (event < 0) {
            if (mTXVodPlayer == player) {
                TXLog.i(TAG, "onPlayEvent, event prepared, player = " + player);

                String desc = null;
                switch (event) {
                    case TXLiveConstants.PLAY_ERR_GET_RTMP_ACC_URL_FAIL:
                        desc = "获取加速拉流地址失败";
                        break;
                    case TXLiveConstants.PLAY_ERR_FILE_NOT_FOUND:
                        desc = "文件不存在";
                        break;
                    case TXLiveConstants.PLAY_ERR_HEVC_DECODE_FAIL:
                        desc = "h265解码失败";
                        break;
                    case TXLiveConstants.PLAY_ERR_HLS_KEY:
                        desc = "HLS解密key获取失败";
                        break;
                    case TXLiveConstants.PLAY_ERR_GET_PLAYINFO_FAIL:
                        desc = "获取点播文件信息失败";
                        break;
                }
                TCUserMgr.getInstance().uploadLogs("vodplay", TCUserMgr.getInstance().getUserId(), event, desc, new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.i(TAG, "onFailure");
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        Log.i(TAG, "onResponse");
                    }
                });
            }
            Toast.makeText(mApplication, "event:" + event, Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onNetStatus(TXVodPlayer player, Bundle status) {

    }

    int i = 0;

    private void initDatas() {
        mInitTCLiveInfoPosition = 0;

        mDownloadProgressDialog = new ProgressDialog(mActivity);
        mDownloadProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); // 设置进度条的形式为圆形转动的进度条
        mDownloadProgressDialog.setCancelable(false);                           // 设置是否可以通过点击Back键取消
        mDownloadProgressDialog.setCanceledOnTouchOutside(false);               // 设置在点击Dialog外是否取消Dialog进度条

        mVerticalViewPager = mView.findViewById(R.id.vertical_view_pager);
        mVerticalViewPager.setOffscreenPageLimit(2);
        mVerticalViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                if (mCurrentPosition != position) {
                    if (mIvPlay != null) {
                        mIvPlay.setVisibility(View.INVISIBLE);
                    }
                }
                i++;
                mCurrentPosition = position;
                // 滑动界面，首先让之前的播放器暂停，并seek到0
                if (mTXVodPlayer != null) {
                    System.out.println("mTXVodPlayer = " + i + "   " + mTXVodPlayer);
                    mTXVodPlayer.seek(0);
                    mTXVodPlayer.pause();
                }
                if (mTCLiveInfoList.size() - 2 < mCurrentPosition) {
                    getNeedVideoData();
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                System.out.println(state);
            }
        });

        mVerticalViewPager.setPageTransformer(false, new ViewPager.PageTransformer() {
            @Override
            public void transformPage(View page, float position) {
                if (position != 0) {
                    return;
                }

                ViewGroup viewGroup = (ViewGroup) page;
                mIvCover = viewGroup.findViewById(R.id.player_iv_cover);
                mIvPlay = viewGroup.findViewById(R.id.tx_video_play);
                mIvPlay.setVisibility(View.INVISIBLE);
                mTXCloudVideoView = viewGroup.findViewById(R.id.player_cloud_view);
                mTXCloudVideoView.setOnClickListener(new View.OnClickListener() {
                    @Override// 点击暂停事件
                    public void onClick(View v) {
                        if (mTXVodPlayer == null) return;
                        if (playerController.isShowRedPacketDialog()) {
                            playerController.hideRedPacketDialog();
                            return;
                        }
                        if (mTXVodPlayer.isPlaying()) {
                            mTXCloudVideoView.onPause();
                            mTXVodPlayer.pause();
                            if (mIvPlay != null) {
                                mIvPlay.setVisibility(View.VISIBLE);
                            }
                        } else {
                            mTXCloudVideoView.onResume();
                            mTXVodPlayer.resume();
                            if (mIvPlay != null) {
                                mIvPlay.setVisibility(View.INVISIBLE);
                            }
                        }
                    }
                });
                PlayerInfo playerInfo = mPagerAdapter.findPlayerInfo(mCurrentPosition);
                if (playerInfo != null) {
                    if (isVisibleToUser) {
                        mTXCloudVideoView.onResume();
                        playerInfo.txVodPlayer.resume();
                        if (mIvPlay != null) {
                            mIvPlay.setVisibility(View.INVISIBLE);
                        }
                    }
                    if (mTXVodPlayer != null) mTXVodPlayer.pause();
                    mTXVodPlayer = playerInfo.txVodPlayer;
                }
            }
        });

        mPagerAdapter = new VideoListPagerAdapter();
        mVerticalViewPager.setAdapter(mPagerAdapter);
    }

    private void initPlayerSDK() {
        mVerticalViewPager.setCurrentItem(mInitTCLiveInfoPosition);
    }

    private void initPhoneListener() {
        if (mPhoneListener == null)
            mPhoneListener = new TXPhoneStateListener(mTXVodPlayer);
        TelephonyManager tm = (TelephonyManager) mApplication.getSystemService(Service.TELEPHONY_SERVICE);
        tm.listen(mPhoneListener, PhoneStateListener.LISTEN_CALL_STATE);
    }

    public void restartPlay() {
        if (mTXVodPlayer != null && isVisibleToUser) {
            mTXVodPlayer.resume();
            mIvPlay.setVisibility(View.INVISIBLE);
        }
    }

    class FollowMapItemBean {
        String shopId;
        ImageView imageView;

        public FollowMapItemBean(String shopId, ImageView imageView) {
            this.shopId = shopId;
            this.imageView = imageView;
        }

        public String getShopId() {
            return shopId;
        }

        public void setShopId(String shopId) {
            this.shopId = shopId;
        }

        public ImageView getImageView() {
            return imageView;
        }

        public void setImageView(ImageView imageView) {
            this.imageView = imageView;
        }
    }

    LinkedHashMap<Integer, FollowMapItemBean> followMap = new LinkedHashMap<>();

    class VideoListPagerAdapter extends PagerAdapter {
        ArrayList<PlayerInfo> playerInfoList = new ArrayList<>();

        protected PlayerInfo instantiatePlayerInfo(int position) {
            PlayerInfo playerInfo = new PlayerInfo();
            TXVodPlayer vodPlayer = new TXVodPlayer(mActivity);
            vodPlayer.setRenderRotation(TXLiveConstants.RENDER_ROTATION_PORTRAIT);
            vodPlayer.setRenderMode(TXLiveConstants.RENDER_MODE_ADJUST_RESOLUTION);
            vodPlayer.setVodListener(ShareFragment.this);
            TXVodPlayConfig config = new TXVodPlayConfig();
            config.setCacheFolderPath(Environment.getExternalStorageDirectory().getPath() + "/txcache");
            config.setMaxCacheItems(5);
            vodPlayer.setConfig(config);
            vodPlayer.setAutoPlay(false);

            PlayerInfoBean tcLiveInfo = mTCLiveInfoList.get(position);
            playerInfo.playURL = tcLiveInfo.getVideoURL();
            playerInfo.txVodPlayer = vodPlayer;
            playerInfo.reviewstatus = TCVideoInfo.REVIEW_STATUS_NORMAL;
            playerInfo.pos = position;
            playerInfoList.add(playerInfo);

            return playerInfo;
        }

        protected void destroyPlayerInfo(int position) {
            while (true) {
                PlayerInfo playerInfo = findPlayerInfo(position);
                if (playerInfo == null)
                    break;
                playerInfo.txVodPlayer.stopPlay(true);
                playerInfoList.remove(playerInfo);
                TXCLog.d(TAG, "destroyPlayerInfo " + position);
            }
        }

        public PlayerInfo findPlayerInfo(int position) {
            for (int i = 0; i < playerInfoList.size(); i++) {
                PlayerInfo playerInfo = playerInfoList.get(i);
                if (playerInfo.pos == position) {
                    return playerInfo;
                }
            }
            return null;
        }

        public PlayerInfo findPlayerInfo(TXVodPlayer player) {
            for (int i = 0; i < playerInfoList.size(); i++) {
                PlayerInfo playerInfo = playerInfoList.get(i);
                if (playerInfo.txVodPlayer == player) {
                    return playerInfo;
                }
            }
            return null;
        }

        public void onDestroy() {
            for (PlayerInfo playerInfo : playerInfoList) {
                playerInfo.txVodPlayer.stopPlay(true);
            }
            playerInfoList.clear();
        }

        @Override
        public int getCount() {
            return mTCLiveInfoList.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            ((MainActivity) getActivity()).setUpdateTab(newPayCount > 0 ? newPayCount-- : 0);
            PlayerInfoBean tcLiveInfo = mTCLiveInfoList.get(position);
            View view = LayoutInflater.from(container.getContext()).inflate(R.layout.tc_view_player_content_copy, null);
            view.setId(position);
            // 封面
            ImageView coverImageView = view.findViewById(R.id.player_iv_cover);
            TCUtils.blurBgPic(mActivity, coverImageView, tcLiveInfo.getCoverURL(), R.mipmap.bg);
            // 头像
            CircleImageView ivAvatar = view.findViewById(R.id.civ);
            RequestBuilder<Drawable> errorBuilder = Glide.with(mFragment).load(R.mipmap.logo);
            Glide.with(mFragment).load(tcLiveInfo.getHomeImg()).error(errorBuilder).into(ivAvatar);
            // 姓名
            TextView tvName = view.findViewById(R.id.player_tv_publisher_name);
            if (TextUtils.isEmpty(tcLiveInfo.getShopName()) || "null".equals(tcLiveInfo.getShopName())) {
                tvName.setText(TCUtils.getLimitString(tcLiveInfo.getShopId() + "", 10));
            } else {
                tvName.setText("@" + tcLiveInfo.getShopName());
            }

            TextView tvVideoReviewStatus = view.findViewById(R.id.tx_video_review_status);
            tvVideoReviewStatus.setVisibility(View.GONE);

            // 获取此player
            TXCloudVideoView playView = view.findViewById(R.id.player_cloud_view);
            PlayerInfo playerInfo = instantiatePlayerInfo(position);
            playerInfo.playerView = playView;
            playerInfo.txVodPlayer.setPlayerView(playView);

            if (playerInfo.reviewstatus == TCVideoInfo.REVIEW_STATUS_NORMAL) {
                playerInfo.txVodPlayer.startPlay(playerInfo.playURL);
            } else if (playerInfo.reviewstatus == TCVideoInfo.REVIEW_STATUS_NOT_REVIEW) { // 审核中
            } else if (playerInfo.reviewstatus == TCVideoInfo.REVIEW_STATUS_PORN) {       // 涉黄

            }

            // 视频描述
            final MyClickListener myClickListener = new MyClickListener(position, view);
            TextView descTv = view.findViewById(R.id.player_tv_publisher_desc);
            descTv.setText(TextUtils.isEmpty(tcLiveInfo.getDescribe()) ? "用户没有填写描述哟~~~!" : tcLiveInfo.getDescribe());
            loadingDetail(view, position, tcLiveInfo, myClickListener);

            ImageView commentIv = view.findViewById(R.id.iv_comment);

            ivAvatar.setOnClickListener(myClickListener);
            tvName.setOnClickListener(myClickListener);
            commentIv.setOnClickListener(myClickListener);
            container.addView(view);
            return view;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            followMap.remove(position);
            destroyPlayerInfo(position);
            container.removeView((View) object);
        }
    }

    /**
     * 加载单条视频的 是否有红包 关注数量 是否点赞。。。
     *
     * @param view
     * @param tcLiveInfo
     * @param myClickListener
     */
    private void loadingDetail(View view, int position, PlayerInfoBean tcLiveInfo, MyClickListener myClickListener) {
        VideoDetail videoDetail = tcLiveInfo.getVideoDetail();
        if (videoDetail == null || videoDetail.getExpireTime() < System.currentTimeMillis()) {
            addDisposableIoMain(videoService.getVideoDetail(tcLiveInfo.getShopId(), tcLiveInfo.getVideoId()), new DefaultConsumer<VideoDetail>(mApplication) {
                @Override
                public void operateSuccess(BaseResult<VideoDetail> result) {
                    VideoDetail data = result.getData();
                    tcLiveInfo.setVideoDetail(data);
                    setItemVideoDetail(view, position, data, myClickListener);
                }
            });
        } else {
            setItemVideoDetail(view, position, videoDetail, myClickListener);
        }
    }


    /**
     * 设置单条视频的 是否有红包 关注数量 是否点赞。。。
     *
     * @param view
     * @param data
     */
    private void setItemVideoDetail(View view, int position, VideoDetail data, MyClickListener myClickListener) {
        TextView followTv = view.findViewById(R.id.tv_follow);
        followTv.setText(data.getConcernNum() + "");
        TextView favoriteTv = view.findViewById(R.id.tv_favorite);
        favoriteTv.setText(data.getNiceNum() + "");
        TextView commentTv = view.findViewById(R.id.tv_comment);
        commentTv.setText(data.getCommentNum() + "");
        ImageView followIv = view.findViewById(R.id.iv_follow);
        followIv.setOnClickListener(myClickListener);
        followIv.setVisibility(data.getUserIsConcern() == 1 ? View.INVISIBLE : View.VISIBLE);
        View red_desc_tv = view.findViewById(R.id.red_desc_tv);
        data.setRedBagView(red_desc_tv);
        handleRedBag(position);
        ShineButton favoriteIv = view.findViewById(R.id.iv_favorite);
        favoriteIv.setOnClickListener(myClickListener);
        favoriteIv.setChecked(data.getUserIsNice() == 1);
        favoriteIv.setOnCheckStateChangeListener((View view1, boolean checked) -> {
            myClickListener.handleFavorite(checked);
        });
        followMap.put(position, new FollowMapItemBean(data.getShopId(), followIv));
    }

    /**
     * 处理红包提示文字  是否显示 商家名称头上的文字
     *
     * @param position
     */
    public void handleRedBag(int position) {
        VideoDetail videoDetail = mTCLiveInfoList.get(position).getVideoDetail();
        if (videoDetail.getHaveRedBag() == 0) {
            ((View) videoDetail.getRedBagView()).setVisibility(View.GONE);
        } else {
            ((View) videoDetail.getRedBagView()).setVisibility(View.VISIBLE);
        }
    }

    private class MyClickListener implements View.OnClickListener, TCVodPlayerController.TCVodPlayerListener {
        int position;
        ImageView followIv;
        TextView followTv;
        ShineButton favoriteIv;
        TextView favoriteTv;
        ImageView commentIv;
        TextView commentTv;

        public MyClickListener(int position, View view) {
            this.position = position;
            followIv = view.findViewById(R.id.iv_follow);
            followTv = view.findViewById(R.id.tv_follow);
            favoriteIv = view.findViewById(R.id.iv_favorite);
            favoriteTv = view.findViewById(R.id.tv_favorite);
            commentIv = view.findViewById(R.id.iv_comment);
            commentTv = view.findViewById(R.id.tv_comment);
        }

        @Override
        public void followSuccess(int position, boolean flag) {
            PlayerInfoBean tcLiveInfo = mTCLiveInfoList.get(position);
            VideoDetail videoDetail = tcLiveInfo.getVideoDetail();
            videoDetail.setConcernNum(videoDetail.getConcernNum() + 1);
            followIv.setImageResource(R.mipmap.bg_followed);
            followTv.setText(videoDetail.getConcernNum() + "");
            videoDetail.setUserIsConcern(1);
            followIv.setVisibility(videoDetail.getUserIsConcern() == 1 ? View.INVISIBLE : View.VISIBLE);
            String shopId = tcLiveInfo.getShopId();
            for (PlayerInfoBean bean : mTCLiveInfoList) {
                if (shopId != bean.getShopId()) continue;
                bean.getVideoDetail().setUserIsConcern(1);
            }
            for (Map.Entry<Integer, FollowMapItemBean> it : followMap.entrySet()) {
                if (it.getValue().getShopId() != shopId) continue;
                it.getValue().getImageView().setVisibility(View.INVISIBLE);
            }
        }

        @Override
        public void followFailed(int position, boolean flag) {
            PlayerInfoBean tcLiveInfo = mTCLiveInfoList.get(position);
            VideoDetail videoDetail = tcLiveInfo.getVideoDetail();
            followIv.setImageResource(R.mipmap.bg_un_follow);
            followTv.setText(videoDetail.getConcernNum() + "");
            videoDetail.setUserIsConcern(0);
            followIv.setVisibility(videoDetail.getUserIsConcern() == 1 ? View.GONE : View.VISIBLE);
            String shopId = tcLiveInfo.getShopId();
            for (PlayerInfoBean bean : mTCLiveInfoList) {
                if (shopId != bean.getShopId()) continue;
                bean.getVideoDetail().setUserIsConcern(0);
            }
            for (Map.Entry<Integer, FollowMapItemBean> it : followMap.entrySet()) {
                if (it.getValue().getShopId() != shopId) continue;
                it.getValue().getImageView().setVisibility(View.VISIBLE);
            }
        }

        @Override
        public void favoriteSuccess(int position, boolean flag) {
            VideoDetail tcLiveInfo = mTCLiveInfoList.get(position).getVideoDetail();
            if (flag) { // 关注
                tcLiveInfo.setNiceNum(tcLiveInfo.getNiceNum() + 1);
            } else {
                tcLiveInfo.setNiceNum(tcLiveInfo.getNiceNum() - 1);
            }
            favoriteTv.setText(tcLiveInfo.getNiceNum() + "");
            tcLiveInfo.setUserIsNice(flag ? 1 : 0);
        }

        @Override
        public void favoriteFailed(int position, boolean flag) {
            PlayerInfoBean tcLiveInfo = mTCLiveInfoList.get(position);
            favoriteIv.setChecked(!flag);
            tcLiveInfo.getVideoDetail().setUserIsNice(flag ? 0 : 1);
        }

        /**
         * 点赞操作处理
         *
         * @param checked
         */
        public void handleFavorite(boolean checked) {
            PlayerInfoBean tcLiveInfo = mTCLiveInfoList.get(position);
            String videoId = tcLiveInfo.getVideoId();
            if (checked) {
                playerController.addFavorite(favoriteIv, position, videoId, this);
            } else {
                playerController.cancelFavorite(favoriteIv, position, videoId, this);
            }
        }

        @Override
        public void onClick(View v) {
            PlayerInfoBean tcLiveInfo = mTCLiveInfoList.get(position);
            String shopId = tcLiveInfo.getShopId();
            switch (v.getId()) {
                case R.id.civ:
                case R.id.player_civ_avatar:
                case R.id.player_tv_publisher_name:
                    showShopDetail(position);
                    break;
                case R.id.iv_follow://关注数量
                    if (tcLiveInfo.getVideoDetail().getUserIsConcern() == 1) return;
                    playerController.addAttention(followIv, position, shopId, this);
                    break;
                case R.id.iv_comment:
                    commentIv.setEnabled(false);
                    commentIv.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            commentIv.setEnabled(true);
                        }
                    }, 500L);
                    showCommentList(position, commentTv);
                    break;
            }
        }
    }

    /**
     * 跳转到商家详情界面
     *
     * @param position
     */
    private void showShopDetail(int position) {
        mActivity.startActivity(ShopDetailActivity.class, "shopId", mTCLiveInfoList.get(position).getShopId() + "");
    }

    /**
     * 获取评论列表数据
     *
     * @param position
     */
    private void showCommentList(final int position, final TextView commentTv) {
        PlayerInfoBean tcLiveInfo = mTCLiveInfoList.get(position);
        final String videoId = tcLiveInfo.getVideoId();
        addDisposableIoMain(videoCommentService.listVideoComment(videoId), new DefaultConsumer<List<VideoCommentBean>>(mApplication) {
            @Override
            public void operateSuccess(BaseResult<List<VideoCommentBean>> result) {
                if (result == null) {
                    showCommentListDialog(position, commentTv, new ArrayList(), videoId);
                } else {
                    showCommentListDialog(position, commentTv, result.getData(), videoId);
                }
            }
        });
    }

    /**
     * 显示评论列表弹窗
     */
    private void showCommentListDialog(final int position, final TextView commentTv, final List<VideoCommentBean> dataList, final String videoId) {
        DialogController.showVideoCommentList(mActivity, dataList, new AddVideoCommentListener() {
            @Override
            public void addComment(String str, Dialog dialog) {
                addVideoComment(position, commentTv, dataList, videoId, str, dialog);
            }
        });
    }

    /**
     * 添加评论
     *
     * @param position
     * @param commentTv
     * @param dataList
     * @param videoId
     * @param str
     * @param dialog
     */
    private void addVideoComment(final int position, final TextView commentTv, final List<VideoCommentBean> dataList, String videoId, final String str, final Dialog dialog) {
        ((BaseActivity) mActivity).showLoadingDialog("正在提交评论...");
        addDisposableIoMain(videoCommentService.addVideoComment(videoId, str), new DefaultConsumer<GrabRedPacketBean>(mApplication) {
            @Override
            public void operateSuccess(BaseResult<GrabRedPacketBean> result) {
                VideoDetail tcLiveInfo = mTCLiveInfoList.get(position).getVideoDetail();
                tcLiveInfo.setCommentNum(tcLiveInfo.getCommentNum() + 1);
                commentTv.setText(tcLiveInfo.getCommentNum() + "");
                VideoCommentBean vcb = new VideoCommentBean();
                vcb.setCreate(System.currentTimeMillis());
                vcb.setModified(System.currentTimeMillis());
                vcb.setCommentIcon(mApplication.getUser().getIcon());
                vcb.setCommentNickname(mApplication.getUser().getNickname());
                vcb.setContent(str);
                ((VideoCommentDialog) dialog).showCommentList(vcb);
                ((BaseActivity) mActivity).hideAlertDialog();
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {
                ((BaseActivity) mActivity).hideAlertDialog();
                showToast("提交评论失败==" + throwable.getMessage());
            }
        });
    }

    static class TXPhoneStateListener extends PhoneStateListener {
        WeakReference<TXVodPlayer> mPlayer;

        public TXPhoneStateListener(TXVodPlayer player) {
            mPlayer = new WeakReference<TXVodPlayer>(player);
        }

        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
            super.onCallStateChanged(state, incomingNumber);
            TXVodPlayer player = mPlayer.get();
            switch (state) {
                //电话等待接听
                case TelephonyManager.CALL_STATE_RINGING:
                    if (player != null) player.setMute(true);
                    break;
                //电话接听
                case TelephonyManager.CALL_STATE_OFFHOOK:
                    if (player != null) player.setMute(true);
                    break;
                //电话挂机
                case TelephonyManager.CALL_STATE_IDLE:
                    if (player != null) player.setMute(false);
                    break;
            }
        }
    }

    @Subscribe
    public void onEventFromLogin(ReLoginSuccessEvent reLoginSuccessEvent) {
        getNeedVideoData();
    }
}
